package app.qrcode.browser.ykpixabay.ui.viewpic

import android.graphics.drawable.Drawable
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.Fragment
import app.qrcode.browser.ykpixabay.R
import app.qrcode.browser.ykpixabay.util.OperatePicUtil
import com.bumptech.glide.Glide
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import kotlinx.android.synthetic.main.fragment_see_pic.*
import kotlinx.android.synthetic.main.star_item.view.*

/**
 * Created by YiGo on 2022/5/2.
 */
class seePicFragment : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_see_pic, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        val webformatURL: String? = arguments?.getString("webformatURL")
        Glide.with(view)
            .load(webformatURL)
            .listener(object : RequestListener<Drawable> {
                override fun onLoadFailed(
                    e: GlideException?,
                    model: Any?,
                    target: Target<Drawable>?,
                    isFirstResource: Boolean
                ): Boolean {
                    Log.w("cdm", "seePicFragment.onLoadFailed -> 没加载就失败")
                    return false
                }

                override fun onResourceReady(
                    resource: Drawable?,
                    model: Any?,
                    target: Target<Drawable>?,
                    dataSource: DataSource?,
                    isFirstResource: Boolean
                ): Boolean {
                    return false.also {
                    }
                }

            })
            .placeholder(R.drawable.ic_baseline_insert_photo_24)
            .into(touch_imageview)

            touch_imageview.setOnLongClickListener {
                AlertDialog.Builder(this.requireContext()).apply {
                    setTitle("你要保存这张图片吗")
                    setPositiveButton(
                        "确定"
                    ) { _, _ ->
                        if (webformatURL != null) {
                            OperatePicUtil.savePicByBm(context,webformatURL)
                        }
                    }
                    setNegativeButton(
                        "取消"
                    ) { _, _ ->

                    }
                }.create().show()
                true
            }
    }
}